package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.http.okhttp.HttpTask;
import com.lib.util.ScreenUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.XApplication;
import com.qbw.app.databinding.VehicleActivityWarningBinding;
import com.qbw.app.model.EventType;
import com.qbw.app.model.Vehicle;
import com.qbw.app.model.Warning;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.vehicle.adapter.VehicleAdapter;
import com.qbw.app.module.vehicle.popwindow.VehicleFilterPopWindow;
import com.qbw.app.request.impl.VehicleRequest;
import com.qbw.core.holder.EmptyHolder;
import com.qbw.core.model.Empty;
import com.qbw.customview.RefreshLoadMoreLayout;

import java.util.ArrayList;
import java.util.List;

import static com.qbw.app.module.vehicle.adapter.VehicleViewType.VT_ALARM_ITEM;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_ALARM_LIST;

/**
 * @author QBW
 * @date 2019-09-02
 */
public class VehicleWarningActivity extends CommonActivity<VehicleActivityWarningBinding> implements VehicleFilterPopWindow.Listener {

    private VehicleAdapter mVehicleAdapter;
    private List<String> mAlarmIds;
    private List<String> mVehicleCodes;
    private Vehicle mVehicle;
    private int mPageNo;

    private VehicleFilterPopWindow vehicleFilterPopWindow;

    public static void startActivity(Context context, Vehicle vehicle) {
        Intent intent = new Intent(context, VehicleWarningActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_VEHICLE, vehicle);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_warning;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mVehicle = (Vehicle) args.getSerializable(Constant.KEY_VEHICLE);
        mBinding.title.setSubTitleVisible(true);
        mBinding.title.setSubTitle(mVehicle.getVehicleNick());
        mBinding.title.setListener(this);
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(this));
        mBinding.rcv.addItemDecoration(new InnerDecoration());
        mVehicleAdapter = new VehicleAdapter(this);
        mBinding.rcv.setAdapter(mVehicleAdapter);
        mBinding.rll.init(new RefreshLoadMoreLayout.Config(this).canLoadMore(true));

        mVehicleCodes = new ArrayList<>();
        mVehicleCodes.add(mVehicle.getVehicleCode());

        mBinding.rll.startAutoRefresh();

        vehicleFilterPopWindow = new VehicleFilterPopWindow(this, mVehicle, this);
    }

    @Override
    public void onRefresh() {
        mPageNo = 1;
        if (getSelectedAlarmIdLength() > 0) {
            mGeneralManager.getRequestManager()
                           .getVehicleRequest()
                           .getAlarmList(mVehicleCodes,
                                         mAlarmIds,
                                         mPageNo,
                                         Constant.PAGESIZE_10,
                                         this)
                           .execute();
        }
        mGeneralManager.getRequestManager()
                       .getVehicleRequest()
                       .getAlarmConfig(mVehicle.getVehicleCode(), this)
                       .execute();
    }

    @Override
    public void onLoadMore() {
        super.onLoadMore();
        mGeneralManager.getRequestManager()
                       .getVehicleRequest()
                       .getAlarmList(mVehicleCodes, mAlarmIds, mPageNo, Constant.PAGESIZE_10, this)
                       .execute();
    }

    @Override
    public void onRightAreaClick() {
        super.onRightAreaClick();
        //new VehicleFilterPopWindow(this, mVehicle, this).showAsDropDown(mBinding.title);
        vehicleFilterPopWindow.showAsDropDown(mBinding.title);
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_ALARM_LIST)) {
            Warning.Response response = (Warning.Response) entity;
            Warning.Data data = response.getData();
            boolean refresh = (int) httpTask.getParams().get("pageCount") == 1;
            if (refresh) {
                mVehicleAdapter.clear();
            }
            if (data.size() > 0) {
                for (Warning w : data.getList()) {
                    w.setVehicleNickName(mVehicle.getVehicleNick());
                }
            }
            mVehicleAdapter.addChild(data.getList());
            boolean noMore = data.size() < Constant.PAGESIZE_10;
            if (!noMore) {
                mPageNo++;
            }
            if (mVehicleAdapter.getChildCount() <= 0) {
                mVehicleAdapter.showEmpty(new Empty(0, EmptyHolder.ModelId.M_VEHICLE_WARNING));
            }
            if (refresh) {
                mBinding.rll.stopRefreshNoMoreData(noMore);
            } else {
                mBinding.rll.stopLoadMoreNoMoreData(noMore);
            }
        } else if (method.equals(VehicleRequest.METHOD_EVENT_TYPE_LIST)) {
            if (getSelectedAlarmIdLength() <= 0) {
                Warning.ResponseList response = (Warning.ResponseList) entity;
                mAlarmIds = response.getAlarmIdList();
                mGeneralManager.getRequestManager()
                               .getVehicleRequest()
                               .getAlarmList(mVehicleCodes,
                                             mAlarmIds,
                                             mPageNo,
                                             Constant.PAGESIZE_10,
                                             this)
                               .execute();
            }
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);

        String method = httpTask.getMethod();
        if (method.equals(METHOD_ALARM_LIST)) {
            boolean refresh = (int) httpTask.getParams().get("pageCount") == 1;
            if (refresh) {
                mBinding.rll.stopRefresh();
            } else {
                mBinding.rll.stopLoadMore();
            }
        } else if (method.equals(VehicleRequest.METHOD_EVENT_TYPE_LIST)) {
            if (getSelectedAlarmIdLength() <= 0) {
                mGeneralManager.getRequestManager()
                               .getVehicleRequest()
                               .getAlarmList(mVehicleCodes,
                                             mAlarmIds,
                                             mPageNo,
                                             Constant.PAGESIZE_10,
                                             this)
                               .execute();
            }
        }
    }

    @Override
    public void onSelectedEventTypes(List<EventType.SubEventType> subEventTypes) {
        int size = subEventTypes == null ? 0 : subEventTypes.size();
        List<String> alarmIds = size <= 0 ? null : new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            alarmIds.add(subEventTypes.get(i).getEventId() + "");
        }
        mAlarmIds = alarmIds;
        mPageNo = 1;
        mGeneralManager.getRequestManager()
                       .getVehicleRequest()
                       .getAlarmList(mVehicleCodes, mAlarmIds, mPageNo, Constant.PAGESIZE_10, this)
                       .execute();
    }

    private int getSelectedAlarmIdLength() {
        return mAlarmIds == null ? 0 : mAlarmIds.size();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(Constant.KEY_VEHICLE, mVehicle);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mGeneralManager.getRequestManager().getVehicleRequest().markAllWarningRead(null).execute();
    }

    private static class InnerDecoration extends RecyclerView.ItemDecoration {

        private Context mContext = XApplication.getInstance();
        private int mSpace10;
        private int mSpace15;

        public InnerDecoration() {
            mSpace10 = ScreenUtil.dp2px(mContext, 10);
            mSpace15 = ScreenUtil.dp2px(mContext, 15);
        }

        @Override
        public void getItemOffsets(Rect outRect,
                                   View view,
                                   RecyclerView parent,
                                   RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            int ap = parent.getChildAdapterPosition(view);
            if (ap == RecyclerView.NO_POSITION) {
                return;
            }
            int vt = parent.getAdapter().getItemViewType(ap);
            if (vt == VT_ALARM_ITEM) {
                outRect.left = mSpace15;
                outRect.right = mSpace15;
                outRect.top = mSpace10;
            }
        }
    }
}
